/**
 * Created by Administrator on 2017/6/1 0001.
 */

import {
    instance as Web
} from '../../../src/Web'

$(function () {
    var TreeNode = Web.getJsVar('node');
    // 角色成员编辑控件
    function roleMemberEditFn(node){
        var xhtml = '<div>'
            + '<p>'+node.text+'</p>'
            + '<p><input class="form-control" type="text" placeholder="根据用户代码搜索用户……" data-key="search"></p>'
            + '<div class="row">'
            + '<div class="col">'
                + '<a href="javascript:;" data-key="remove">移除</a>'
                + '<ul class="list-group" data-key="member"></ul></div>'
            + '<div class="col">'
                + '<a href="javascript:;" data-key="add">加入</a>'
                + '<ul class="list-group" data-key="users"></ul></div>'
            + '</div>'
            + '</div>'
        ;
        var $xhtml = $(xhtml);
        var stackData = [];
        var addUserListFn = function(args){
            var post = {};
            if(args){
                post.args = args;
            }
            $.post(Web._baseurl+'admin/sgroup/uSysUser', post, function(user){
                $.post(Web._baseurl+'admin/sgroup/uRoleMember', {id: node.id}, function(rs){
                    var member = rs.list;                            
                    var userArr = user.list;
                    var memberMap = {};
                    // 运用字典整理
                    for(var j=0; j<member.length; j++){
                        var el = member[j];
                        memberMap[el.user_uid] = el;
                    }
                    // 去存已经存在的用户列表
                    var uXhtml = '';
                    var mXhtml = '';
                    for(var i=0; i<userArr.length; i++){
                        var u = userArr[i];
                        var idx;
                        if(memberMap[u.uid]){
                            idx = stackData.push(u) - 1;
                            mXhtml += '<li class="list-group-item"><label><input type="checkbox" value="'+idx+'">'+u.account+'</label></li>';
                        }else{
                            idx = stackData.push(u) - 1;
                            uXhtml += '<li class="list-group-item"><label><input type="checkbox" value="'+idx+'">'+u.account+'</label></li>';
                        }
                    }
                    $xhtml.find('[data-key="member"]').html(mXhtml);
                    $xhtml.find('[data-key="users"]').html(uXhtml);
                    
                });
            });
        };
        addUserListFn();
        // 事件绑定
        var saveFn = function(dom, type){
            var ipts = dom.parent('.col').find('ul input:checked');
            var sv = {};
            var v = [];
            for(var i=0; i<ipts.length; i++){
                var el = ipts[i];
                var uDt = stackData[el.value];
                v.push(uDt.uid);   
                var ul = $xhtml.find('[data-key="'+(type=='add'? 'member':'users')+'"]');
                var str = '<li class="list-group-item"><label><input type="checkbox" value="'+el.value+'">'+uDt.account+'</label></li>';
                ul.prepend(str);
                $(el).parents('li').remove();                     
            }
            if(v.length > 0){
                sv.v = v;
                sv.roleid = node.id;
                sv.type = type;
                $.post(Web._baseurl+'admin/sgroup/uSaveRoleMember', sv, function(feek){});
            }
        };
        // 移除用户
        $xhtml.find('[data-key="remove"]').click(function(){ saveFn($(this), 'remove');});
        // 加入用户
        $xhtml.find('[data-key="add"]').click(function(){ saveFn($(this), 'add');});
        // 搜索监听
        $xhtml.find('[data-key="search"]').change(function(){
            var value = $(this).val();
            addUserListFn({c: 'account', v: value, e:'like'});
        });
        $('#grp_role_ds').html($xhtml);
    }
    // 创建树形菜单    
    function CreateGroupRoleTree() {
        var data = Web.getJsVar('jstree');
        // console.log(data);
        $('#group_role_tree')
            .on('changed.jstree', function (e, data) {
                // console.log(data);
                var node = data.node;
                // console.log(node.type);
                if(node.type == 'default'){
                    var xhtml = '<p>'
                            + ' <a href="'+Web._baseurl+'admin/sgroup/edit/uid/'+node.id+'.html" class="btn btn-info">编辑</a>'
                            + ' <a href="'+Web._baseurl+'admin/sgroup/edit/uid/'+node.id+'.html" class="btn btn-danger">删除</a>'
                        + '</p>'
                        ;
                    $('#grp_role_ds').html(xhtml);
                }else if(node.type == 'role'){
                    roleMemberEditFn(node);
                }
            })
            .jstree({'core' :
            {
                data:data
            },
            "types" : {
                "#" : {
                    "max_children" : 1,
                    "max_depth" : 4,
                    "valid_children" : ["root"]
                },
                "default" : {
                    "icon" : "fa fa-cubes",
                    "valid_children" : ["default","file"]
                },
                "role" : {
                    "icon" : "fa fa-cube",
                    "valid_children" : []
                }
            },
            "plugins" : [
                'types'
            ]
        });
    }
    function CreateGroupRole() {
        var gj = go.GraphObject.make;
        var myDiagram = gj(
            go.Diagram,'group_role_ds',
            {
                initialContentAlignment: go.Spot.Center, // center Diagram contents
                "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo
            });
        /**
         * go 类型： GraphLinksModel 手动连线,Model, 树形图 TreeModel
         */
        //var myModel = gj(go.Model);
        var myModel = gj(go.GraphLinksModel);

        // in the model data, each node is represented by a JavaScript object:
        console.log(TreeNode);

        myModel.nodeDataArray = TreeNode;
        myModel.linkDataArray = [];
        (function () {
            for(var k=0; k<TreeNode.length; k++){
                var nd = TreeNode[k];
                if(nd.group){
                    myModel.linkDataArray.push({from:nd.group,to:nd.key});
                }
            }
            console.log(myModel.linkDataArray);
        }());

        myDiagram.model = myModel;
    }
    // jstree 构图
    CreateGroupRoleTree();
    // goJs 构图
    CreateGroupRole();
});